import React, {useState} from "react";
import {Form, Input, Modal, Select} from "antd";
import useGetDict from "@/hooks/useGetDict.ts";
import {selectOptions} from "@/components/DictTag";
import {globalMessageApi} from "@/components/OpComponent/Message";
import {addTagUrl, editTagUrl} from "@/api/blog/tags.ts";


export default React.forwardRef((props: any, ref: any) => {

    const {
        getList
    } = props
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false)

    const dictData = useGetDict("art_category", "art_tag", "status")

    const [form] = Form.useForm()
    const [formValues, setFormValues] = useState<any>();

    const handleOk = () => {
        form.validateFields().then((values) => {
            if (isModalEdit) {
                editTagUrl({
                    ...values,
                    btId: formValues?.btId,
                }).then((res: any) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })
            } else {
                addTagUrl(values).then((res) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })
            }
        })
    };


    const handleCancel = () => {
        setIsModalOpen(false);
    }

    const openModal = (data = {btId: null}) => {
        if (data && data.btId) {
            setIsModalEdit(true)
            form.setFieldsValue(data)
            setFormValues(data);
            setIsModalOpen(true)
        } else {
            setIsModalEdit(false)
            setIsModalOpen(true)
        }
    }

    React.useImperativeHandle(ref, () => ({
        openModal: openModal
    }))
    return <Modal title={isModalEdit ? "编辑标签" : "新增标签"}
                  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                  modalRender={(dom) => (
                      <Form form={form} initialValues={formValues}>
                          {dom}
                      </Form>
                  )}
    >
        <Form.Item name={"btName"} label="标签名称"
                   rules={[{required: true, message: '标签名称不能为空!'}]}>
            <Input placeholder="请输入标签名称"/>
        </Form.Item>
        <Form.Item name={"icon"} label="标签 icon"
                   rules={[{required: true, message: '请选择文章分类!'}]}
        >
            <Select placeholder={'请选择文章分类'}>
                {selectOptions(dictData.art_category)}
            </Select>
        </Form.Item>
    </Modal>
})
